Skip to main content

Unique Paths

LeetCode 62 | Difficulty: Medium​

Medium

Problem Description​

There is a robot on an m x n grid. The robot is initially located at the top-left corner (i.e., grid[0][0]). The robot tries to move to the bottom-right corner (i.e., grid[m - 1][n - 1]). The robot can only move either down or right at any point in time.

Given the two integers m and n, return the number of possible unique paths that the robot can take to reach the bottom-right corner.

The test cases are generated so that the answer will be less than or equal to 2 * 10^9.

Example 1:

Input: m = 3, n = 7
Output: 28

Example 2:

Input: m = 3, n = 2
Output: 3
Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

Constraints:

- `1 <= m, n <= 100`

Topics: Math, Dynamic Programming, Combinatorics


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

Mathematical​

Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.

When to use

Problems with clear mathematical structure, counting, number properties.


Solutions​

Solution 1: C# (Best: 48 ms)​

MetricValue
Runtime48 ms
MemoryN/A
Date2018-03-06
Solution
public class Solution {
public int UniquePaths(int m, int n) {

int[,] dp = new int[m,n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if(i==0|| j==0) dp[i,j] = 1;
else dp[i,j] = dp[i-1,j]+dp[i,j-1];
}
}
return dp[m-1,n-1];
}
}

Complexity Analysis​

ApproachTimeSpace
DP (2D)$O(n Γ— m)$$O(n Γ— m)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.